package tk.mybatis.mapper.entity;

import java.util.ArrayList;
import java.util.List;

import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.SqlNestdHelper;


/**
 * 
 * title: NestdEntityContext.java 
 * description
 *
 * @author rplees
 * @email rplees.i.ly@gmail.com
 * @version 1.0  
 * @created Jul 4, 2016 1:42:36 PM
 */
public class NestdEntityContext {
	List<NestdEntity> list;
	Class<?> clazz;
	EntityTable entityTable;
	
	public NestdEntityContext(Class<?> clazz) {
		list = new ArrayList<NestdEntity>();
		
		this.clazz = clazz;
		entityTable = EntityHelper.getEntityTable(clazz);
	}
	
	public void record(NestdEntity nestdEntity) {
		list.add(nestdEntity);
	}
	
	public String getPreAliasSuffix() {
		if(list.size() < 2)
			return SqlNestdHelper.getTableAliasIfNeed(clazz);
		
		List<NestdEntity> subList = list.subList(0, list.size() - 1);
		return _get(subList);
	}
	
	public String getOGNLTestSuffix() {
		if(isEmpty()) {
			return null;
		}

		String suffix = "";
		for (NestdEntity nestdEntity : list) {
			if(nestdEntity.field.isCollection()) {
				//只取第一个
				suffix += nestdEntity.field.getName() + "[0].";
			} else {
				suffix += nestdEntity.field.getName() + ".";
			}
		}
		
		suffix = suffix.substring(0, suffix.length() - 1);
		return suffix;
	}
	
	public boolean isEmpty() {
		return list.size() < 1;
	}
	
	public String getAliasSuffix() {
		return _get(list);
	}
	
	String _get(List<NestdEntity> list) {
		if(isEmpty())
			return SqlNestdHelper.getTableAliasIfNeed(clazz);
		
		String suffix = "";
		for (NestdEntity nestdEntity : list) {
			suffix += nestdEntity.getProperty() + "_";
		}
		
		suffix = suffix.substring(0, suffix.length() - 1);
		return suffix;
	}

	public void clear() {
		list.clear();
	}
}